﻿using Microsoft.Extensions.DependencyInjection;
using RuoVea.ExConfig;
using RuoVea.ExUtil;
using System;

namespace RuoVea.ExWeb.Cors
{
    /// <summary>
    /// IOptions 扩展
    /// </summary>
    public static class CorsIOptions
    {
        /// <summary>
        /// 注入 配置化的CorsUrls 
        /// </summary>
        /// <param name="services"></param>
        public static void CorsUrls(this IServiceCollection services)
        {
            String corsUrls = Appsettings.app("Cors", "CorsUrls")?.ToString() ?? "*";

            int preflightMaxAge = Appsettings.app("Cors", "PreflightMaxAge").ToIntOrNull() ?? 2520;

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder =>
                    {
                        builder.WithOrigins(corsUrls.Split(","))
                        //添加预检请求过期时间
                         .SetPreflightMaxAge(TimeSpan.FromSeconds(preflightMaxAge))
                        //如果不需要跨域请注释掉.AllowCredentials()或者增加跨域策略
                        .AllowCredentials()
                        .AllowAnyHeader().AllowAnyMethod();
                    });
            });

            //#region Configure Cors

            //services.AddCors(options => options.AddPolicy(_defaultCorsPolicyName,
            //    builder => builder.WithOrigins(
            //            Configuration["Application:CorsOrigins"]
            //            .Split(",", StringSplitOptions.RemoveEmptyEntries).ToArray()
            //        )
            //    .AllowAnyHeader()
            //    .AllowAnyMethod()
            //    .AllowCredentials()));

            //#endregion
        }
    }
}
